﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using static Win32API.WinApi;
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;

namespace JoinBox.JoinBox_Code.WPF.多文档标签.View
{
    public partial class InsideForm : Form
    {
        public InsideForm()
        {
            InitializeComponent();
            Load += InsideForm_Load;
            SizeChanged += InsideForm_SizeChanged;
        }

        private void InsideForm_SizeChanged(object sender, EventArgs e)
        {
            RefreshDocWindow();
        }

        private void RefreshDocWindow()
        {
            if (_DocWindow != IntPtr.Zero)
            {
                //已经嵌入了,所以是0,0位置
                MoveWindow(_DocWindow, 0, 0, Width, Height, true);
            }
        }

        IntPtr _DocWindow = IntPtr.Zero;
        private void InsideForm_Load(object sender, EventArgs e)
        {
            var _ACAD_Handle = Acap.MainWindow.Handle;

            // elementHost1.Child = new DocWindow();

#if true
            //新建进程,用win32修改样式,嵌入到cad
            var p = new Process();
            p.StartInfo.FileName = @"H:\解决方案_dll加载\LabelBar\WpfApp1\bin\Debug\WpfApp1.exe";
            p.StartInfo.CreateNoWindow = false;

            //使 Process 组件等待关联进程进入空闲状态
            if (p.Start() && p.WaitForInputIdle())
            {
                //直到获取了句柄
                while (p.MainWindowHandle == IntPtr.Zero)
                {
                    Thread.Sleep(100);
                    p.Refresh();
                }
                _DocWindow = p.MainWindowHandle;

#if true
                //嵌入WPF面板到WinForm
                SetWindowLong(_DocWindow);
                SetParent(_DocWindow, this.elementHost1.Handle); //改变p的父窗口句柄为本程序句柄
                RefreshDocWindow();

                // ShowWindow(_DocWindow, NCmdShow.SW_SHOWMAXIMIZED);

                //var s = WinApi.GetWindowLong(_DocWindow, (int)GWL.GWL_STYLE);
                //WinApi.SetWindowLong(_DocWindow, GWL.GWL_STYLE, s | (int)WS.WS_MAXIMIZE | ~(int)WS.WS_CAPTION);//最大化|不具有标题栏


                //前置
#endif



            }
#endif
            //嵌入WinForm到CAD
            SetWindowLong(Handle);
            SetParent(Handle, _ACAD_Handle); //改变p的父窗口句柄为本程序句柄
        }
    }
}
